
/*
 * Takes a Date object as param, and returns the relative time span
 * string representation (today, tomorrow, Monday, Yesterday, 1 week ago 
 */
function prettyDate(date){
	if (date == null || !date.getTime) return;
	var td = new Date(); td.setHours(0); td.setMinutes(0);
	td.setSeconds(0); td.setMilliseconds(0); // do it properly
	
	var diff = ((date.getTime() - td.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
	
	if ( isNaN(day_diff))
		return;
	
	// future
	if(day_diff >= 0){
		return day_diff == 0 && "Today" ||
			day_diff == 1 && "Tomorrow" ||
			day_diff < 7 && date.format("dddd") || // this week (Sunday)
			day_diff < 365 && date.format("mmm dd") || // future (Feb 02)
			date.format("mmm dd, yyyy"); // far future (Feb 02, 2012)
	}
	
	// past
	diff = -diff; day_diff = -day_diff; // for convenience
	return day_diff == 1 && "Yesterday" ||
		   day_diff < 7 && day_diff + " days ago" ||
		   day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
		   date.format("mmm dd, yyyy");
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};
